package com.study.study;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author study
 * @version 1.0
 * @date 2020/9/13 22:42
 */

/**
 * ConcurrentModificationException 高并发读写异常
 */
public class NotSafeDemo03 {
    public static void main(String[] args) {

    }

    private static void mapNotSafe() {
        Map<String, String> map = new ConcurrentHashMap<>();
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 8));
                System.out.println(map);
            }, java.lang.String.valueOf(i)).start();
        }
    }

    private static void setNotSafe() {
        //java.util.ConcurrentModificationException
        // Set<String> set = new HashSet<>();
        Set<String> set = new CopyOnWriteArraySet<>();
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                set.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(set);
            }).start();
        }
    }

    private static void listNotSafe() {
        //默认长度10 ，hashmap长度是16
        // ArrayList<String> list = new ArrayList<>();
        // List<String> list = Collections.synchronizedList(new ArrayList<>());

        //写时复制
        List<String> list = new CopyOnWriteArrayList<>();

        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(list);
            }).start();
        }
    }
}
